package threading;

/**
 * @author 徐志荣
 * @date 2023/3/16 14:43
 */

//线程不安全
    class Counter{

        private int count = 0;
        private Object locker = new Object();

        //1.1 锁对象
        public  void add(){
            //锁对象, 在针对那个
            synchronized (this){
                //此处使用 代码块 的方式来表示,
                //进入 synchronized 加锁
                count++;
            }
            //出了 synchronized 解锁
        }

        //1.2. 锁对象,直接给方法使用synchronized
       synchronized public  void add2(){
            count++;
        }

        //2.1 相当于给类对象加锁
        synchronized public static void test(){


        }

        //2.2 相当于给类对象加锁
         public static void test2(){
            synchronized (Counter.class){

            }

        }

        //
        public int get() {
        return count;
        }

        }
public class ThreadDemo13 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        //搞两个线程,两个线程分别对这个 count 自增 5w次
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }

        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }

        });
        thread1.start();
        thread2.start();

        //等待两个线程执行结束,然后看结果
        thread1.join();
        thread2.join();
        System.out.println(counter.get());
    }
}
